import { defineEventHandler, readBody } from 'h3';

export function createProxyStatusApi(app) {
  return defineEventHandler(async (event) => {
    if (event.node.req.method === 'GET') {
      const proxyStatus = app.proxyServer.getStatus();
      const systemProxyStatus = app.systemProxyManager.getStatus();
      
      // 直接返回状态对象，不包装在data中（匹配前端期望）
      const status = {
        // 代理服务器状态
        running: proxyStatus.isRunning,
        enabled: proxyStatus.isRunning && systemProxyStatus.isProxySet, // 综合状态
        isRunning: proxyStatus.isRunning,
        httpPort: proxyStatus.httpPort,
        httpsPort: proxyStatus.httpsPort,
        interceptHttps: proxyStatus.interceptHttps,
        
        // 系统代理状态
        systemProxy: {
          isSet: systemProxyStatus.isProxySet,
          host: systemProxyStatus.proxyHost,
          port: systemProxyStatus.proxyPort
        },
        
        // 其他信息
        connections: proxyStatus.connections,
        certificates: proxyStatus.certificates,
        websocket: {
          connected: app.webSocketServer.getClientCount() > 0,
          clients: app.webSocketServer.getClientCount()
        },
        database: app.database.getStats()
      };

      return status;
    }
  });
}

export function createProxyToggleApi(app) {
  return defineEventHandler(async (event) => {
    console.log(`📨 收到请求: ${event.node.req.method} ${event.node.req.url}`);
    
    if (event.node.req.method === 'POST') {
      console.log('✅ 确认是POST请求，开始处理...');
      try {
        console.log('📖 正在读取请求体...');
        const body = await readBody(event);
        console.log('📖 请求体内容:', body);
        
        const { enabled } = body;
        console.log(`🔄 代理切换请求: ${enabled ? '启用' : '禁用'}`);
        
        // 设置30秒超时
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('代理切换操作超时')), 30000);
        });
        
        const togglePromise = async () => {
          if (enabled) {
            // 启用代理
            console.log('🚀 启用代理，复用系统启动逻辑...');
            await app.startProxy();
          } else {
            // 停用代理 - 复用系统清理逻辑
            console.log('🛑 停用代理，复用系统清理逻辑...');
            await app.stopProxy();
          }
        };
        
        // 执行切换操作，带超时控制
        await Promise.race([togglePromise(), timeoutPromise]);
        
        const status = app.proxyServer.getStatus();
        const systemProxyStatus = app.systemProxyManager.getStatus();
        
        console.log(`✅ 代理切换完成: 代理服务器=${status.running}, 系统代理=${systemProxyStatus.isProxySet}`);
        
        return { 
          data: { 
            running: status.running && systemProxyStatus.isProxySet,
            config: status.config
          }
        };
      } catch (error) {
        console.error('❌ 切换代理状态失败:', error);
        event.node.res.statusCode = 500;
        return { error: error.message };
      }
    } else {
      console.log(`❌ 不支持的请求方法: ${event.node.req.method}`);
      event.node.res.statusCode = 405;
      return { error: 'Method Not Allowed' };
    }
  });
} 